package cn.csc.framework.pay.core.client.impl.jh.util;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.util.*;

public class XMLUtils {

    /**
     * 将Map转换为XML,Map可以多层转
     * @param params 需要转换的map。
     * @param parentName 就是map的根key,如果map没有根key,就输入转换后的xml根节点。
     * @return String-->XML
     */
    @SuppressWarnings("unchecked")
    public static String createXmlByMap(Map<String, Object> map,
                                        String parentName) {
        //获取map的key对应的value
        Map<String, Object> rootMap=(Map<String, Object>)map.get(parentName);
        if (rootMap==null) {
            rootMap=map;
        }
        Document doc = DocumentHelper.createDocument();
        //设置根节点
        doc.addElement(parentName);
        String xml = iteratorXml(doc.getRootElement(), parentName, rootMap);
        return formatXML(xml);
    }
    /**
     * 循环遍历params创建xml节点
     * @param element 根节点
     * @param parentName 子节点名字
     * @param params map数据
     * @return String-->Xml
     */
    @SuppressWarnings("unchecked")
    public static String iteratorXml(Element element, String parentName,
                                     Map<String, Object> params) {
        Element e = element.addElement(parentName);
        Set<String> set = params.keySet();
        for (Iterator<String> it = set.iterator(); it.hasNext();) {
            String key = (String) it.next();
            if (params.get(key) instanceof Map) {
                iteratorXml(e, key, (Map<String, Object>) params.get(key));
            } else if (params.get(key) instanceof List) {
                List<Object> list = (ArrayList<Object>) params.get(key);
                for (int i = 0; i < list.size(); i++) {
                    iteratorXml(e, key, (Map<String, Object>) list.get(i));
                }
            } else {
                String value = params.get(key) == null ? "" : params.get(key)
                        .toString();
                e.addElement(key).addText(value);
                // e.addElement(key).addCDATA(value);
            }
        }
        return e.asXML();
    }
    /**
     * 格式化xml
     * @param xml
     * @return
     */
    public static String formatXML(String xml) {
        String requestXML = null;
        XMLWriter writer = null;
        Document document = null;
        try {
            SAXReader reader = new SAXReader();
            document = reader.read(new StringReader(xml));
            if (document != null) {
                StringWriter stringWriter = new StringWriter();
                OutputFormat format = new OutputFormat(" ", true);// 格式化，每一级前的空格
                format.setNewLineAfterDeclaration(false); // xml声明与内容是否添加空行
                format.setSuppressDeclaration(false); // 是否设置xml声明头部 false：添加
                format.setNewlines(true); // 设置分行
                writer = new XMLWriter(stringWriter, format);
                writer.write(document);
                writer.flush();
                requestXML = stringWriter.getBuffer().toString();
            }
            return requestXML;
        } catch (Exception e1) {
            e1.printStackTrace();
            return null;
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {

                }
            }
        }
    }
    public static void main(String[] args) throws UnsupportedEncodingException {

        try {
            Map<String,Object> param = new HashMap<>();
            param.put("REQUEST_SN","123456");//请求序列号
            param.put("CUST_ID","1");//商户号
            param.put("USER_ID","2");//操作员号
            param.put("PASSWORD","3");//操作员号交易密码
            param.put("TX_CODE","5W1005");
            param.put("LANGUAGE","CN");

            Map<String,Object> body = new HashMap<>();
            body.put("DATE","20231120");//日期
            body.put("KIND","1");//流水状态
            body.put("FILETYPE","1");//1-txt（默认） 2-excel 3-txt+excel（POS商户、龙商户送1；网络特约商户可送1/2/3，对账单下载时间在3秒内为实时返回账单文件名，超过3秒转为异步下载，具体请参考应答报文RETURN_CODE字段说明处理）
            body.put("TYPE","0");
            body.put("NORDERBY","1");
            body.put("POS_CODE","075463386");
            body.put("ORDER","");
            body.put("STATUS","");
            body.put("BILL_FLAG","");
            body.put("Mrch_No","");
            body.put("GROUP_FLAG","");
            param.put("TX_INFO",body);
         String ss= new XMLUtils().createXmlByMap(param,"tx");
         System.out.println(ss);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.exit(0);
    }
}
